const WebSocket = require("ws");
const SessionDB = require("../../files/sessionDb");

class Scoket {
  url;
  ws;
  uWs;
  APPID;
  uid = "001";
  sessionDB;
  msg;

  constructor(url, APPID, uWs, msg) {
    this.url = url;
    this.APPID = APPID;
    this.uWs = uWs;
    this.msg = msg;
    this.ws = new WebSocket(this.url);
    this.ws.on("open", () => {
      this.open();
    });
    this.ws.on("close", () => {
      console.log("连接已关闭，请重新连接");
    });
    this.ws.on("message", (data, flags) => {
      this.message(data, flags);
    });
    this.sessionDB = new SessionDB();
  }

  open() {
    console.log("====已经链接讯飞火星模型====");
    this.send(this.msg);
  }

  async send(message) {
    const history = await this.sessionDB.get(this.uid);
    const tem = {
      header: {
        app_id: this.APPID,
        uid: this.uid,
      },
      parameter: {
        chat: {
          domain: "generalv2",
          temperature: 0.5,
          max_tokens: 1024,
          chat_id: this.uid,
        },
      },
      payload: {
        message: {
          text: [...history, ...[{ role: "user", content: message }]],
        },
      },
    };
    try {
      this.ws.send(JSON.stringify(tem));
      await this.sessionDB.set(this.uid, false, message);
    } catch (error) {
      console.log(error);
    }
  }

  async message(data) {
    const info = JSON.parse(data.toString());
    await this.sessionDB.set(
      this.uid,
      info.header.sid,
      info.payload.choices.text[0].content
    );
    this.uWs.send(
      JSON.stringify({
        sid: info.header.sid,
        message: info.payload.choices.text[0].content,
      })
    );
  }
}

module.exports = Scoket;
